package cn.sjx.graduate.web.controller;

import cn.sjx.graduate.domain.Employee;
import cn.sjx.graduate.domain.Staff;
import cn.sjx.graduate.domain.StaffType;
import cn.sjx.graduate.dto.EmployeeDTO;
import cn.sjx.graduate.dto.PwdDTO;
import cn.sjx.graduate.qo.QueryObject;
import cn.sjx.graduate.service.IEmployeeService;
import cn.sjx.graduate.service.IRedisService;
import cn.sjx.graduate.service.IStaffService;
import cn.sjx.graduate.service.IStaffTypeService;
import cn.sjx.graduate.util.JsonResult;
import cn.sjx.graduate.util.TokenUtil;
import cn.sjx.graduate.vo.EmployeeVO;
import cn.sjx.graduate.web.anno.Log;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author bo-feifei
 * @since 2021-11-07
 */
@RestController
@RequestMapping("/employee")
@Api(tags = "员工相关信息接口")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IStaffService staffService;
    @Autowired
    private IStaffTypeService staffTypeService;

    @GetMapping("query")
    @ApiOperation(value = "分页查询所有员工信息")
    public JsonResult<IPage<Employee>> query(QueryObject qo) {
        return JsonResult.success(employeeService.queryPage(qo));
    }

    @Log(title = "员工删除")
    @DeleteMapping("/delete")
    public JsonResult<?> delete(@RequestParam Long id) {
        if (null == id) {
            return JsonResult.error("被删员工id不能为空");
        }
        Employee employee = employeeService.getById(id);
        employee.setDeleted(1);
        Staff staff = staffService.getOne(new LambdaQueryWrapper<Staff>().eq(Staff::getEmployeeId, id));
        staff.setDeleted(1);
        employeeService.updateById(employee);
        staffService.updateById(staff);
        return JsonResult.success();
    }

    @PostMapping("/save")
    @ApiOperation("新增员工")
    public JsonResult<?> save(@RequestBody EmployeeDTO employee) {
        if (null == employee) {
            return JsonResult.error("参数不能为空");
        }
        employeeService.saveEmployee(employee);
        return JsonResult.success();
    }

    @PostMapping("/update")
    @ApiOperation("修改员工信息")
    public JsonResult<?> update(@RequestBody EmployeeDTO employeeDTO) {
        if (employeeDTO.getId() == null) {
            return JsonResult.error("id不能为空");
        }
        employeeService.updateEmployee(employeeDTO);
        return JsonResult.success();
    }


    @GetMapping("/resetPwd")
    @ApiOperation(value = "将密码重置")
    public JsonResult<Boolean> resetPwd(@RequestParam Long id) {
        Employee user = employeeService.getById(id);
        Md5Hash hashPassword = new Md5Hash("123456", user.getUsername(), 3);
        user.setPassword(hashPassword.toString());
        boolean b = employeeService.saveOrUpdate(user);
        return JsonResult.success(b);
    }

    @PostMapping("/updatePwd")
    @ApiOperation(value = "登录用户修改密码或手机号信息")
    public JsonResult<Boolean> updatePwd(@RequestBody PwdDTO pwdDTO, HttpServletRequest request) {
        String token = TokenUtil.getToken(request);
        Employee employee = redisService.getUserByToken(token);
        String password = employee.getPassword();
        String username = employee.getUsername();
        String oldPwd = pwdDTO.getOldPwd();
        if (StringUtils.isNoneEmpty(password,username,oldPwd)){
            Md5Hash hashOldPwd = new Md5Hash(oldPwd, username, 3);
            if (!hashOldPwd.toString().equals(password)) {
                return JsonResult.error("老密码输入错误");
            }
            if (!pwdDTO.getNewPwd().equals(pwdDTO.getAgainPwd())) {
                return JsonResult.error("两次密码输入不相同");
            }
            Md5Hash hashNewPwd = new Md5Hash(pwdDTO.getNewPwd(), username, 3);
            employee.setPassword(hashNewPwd.toString());
            if (StringUtils.isNotBlank(pwdDTO.getPhone())) {
                employee.setPhone(pwdDTO.getPhone());
            }
        } else {
            if (StringUtils.isNotBlank(pwdDTO.getPhone())) {
                employee.setPhone(pwdDTO.getPhone());
            }
        }
        employeeService.updateById(employee);
        // 更新缓存数据
        redisService.setUserByToken(token,JSON.toJSONString(employee));
        return JsonResult.success();
    }

    @GetMapping("/personalCenter")
    @ApiOperation(value = "个人中心（展示登录用户数据）")
    public JsonResult<EmployeeVO> personalCenter(HttpServletRequest request) {
        String token = TokenUtil.getToken(request);
        Employee userByToken = redisService.getUserByToken(token);
        QueryWrapper<Staff> wrapper = new QueryWrapper<>();
        wrapper.eq("employee_id", userByToken.getId());
        Staff staff = staffService.getOne(wrapper);
        StaffType staffType = staffTypeService.getById(staff.getType());
        EmployeeVO employeeVO = new EmployeeVO();
        BeanUtils.copyProperties(userByToken, employeeVO);
        employeeVO.setDept(staffType.getId());
        employeeVO.setDeptName(staffType.getStaffType());
        if (userByToken.getAdmin()) {
            employeeVO.setAdmin(1);
            employeeVO.setAdminValue("管理员");
        } else {
            employeeVO.setAdmin(0);
            employeeVO.setAdminValue("普通用户");
        }
        return JsonResult.success(employeeVO);
    }
}

